import os
import tempfile
import asyncio
import edge_tts
from algorithms.tts_voice import tts_order_voice

class VoiceGenerator:
    """语音生成器类"""
    
    def __init__(self):
        self.tts_voice_dict = tts_order_voice
    
    def get_supported_languages(self):
        """获取支持的语言列表"""
        return list(self.tts_voice_dict.keys())
    
    async def text_to_speech_async(self, text, language_key, rate=1.0):
        """异步文本转语音核心算法"""
        if not text or not text.strip():
            raise ValueError("文本不能为空")
        
        if language_key not in self.tts_voice_dict:
            raise ValueError(f"不支持的语言: {language_key}")
        
        voice = self.tts_voice_dict[language_key]
        
        # 将语速从1-3范围转换为-50%到+50%范围
        rate_percent = int((rate - 1) * 50)
        # Edge TTS不接受0%，如果为0则使用正常语速
        if rate_percent == 0:
            rate_str = ""
        else:
            rate_str = f"{rate_percent}%"
        
        # 创建临时文件
        with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3", dir=tempfile.gettempdir()) as tmp_file:
            tmp_path = tmp_file.name
        
        try:
            # 使用edge_tts生成语音
            if rate_str:
                communicate = edge_tts.Communicate(text.strip(), voice, rate=rate_str)
            else:
                communicate = edge_tts.Communicate(text.strip(), voice)
            await communicate.save(tmp_path)
            
            return tmp_path
            
        except Exception as e:
            # 清理临时文件
            if os.path.exists(tmp_path):
                os.remove(tmp_path)
            raise Exception(f"语音生成失败: {str(e)}")
    
    def generate_speech(self, text, language_key, rate=1.0):
        """同步生成语音（对外接口）"""
        try:
            audio_path = asyncio.run(self.text_to_speech_async(text, language_key, rate))
            return {
                "success": True,
                "audio_path": audio_path,
                "message": "语音生成成功"
            }
        except Exception as e:
            return {
                "success": False,
                "error": str(e)
            }
    
    def cleanup_audio_file(self, file_path):
        """清理临时音频文件"""
        try:
            if os.path.exists(file_path):
                os.remove(file_path)
                return True
        except Exception:
            pass
        return False

# 创建全局实例
voice_generator = VoiceGenerator()
